import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/views/Home.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    }, {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/Register.vue')
    }, {
      path: '/books',
      name: 'Books',
      component: () => import('@/views/BooksLayout.vue'),
      meta: { requiresAuth: false },
      children: [
        {
          path: '',
          name: 'BookList',
          component: () => import('@/views/book/BookList.vue'),
          meta: { requiresAuth: false }
        },
        {
          path: ':id',
          name: 'BookDetail',
          component: () => import('@/views/book/BookDetail.vue'),
          props: true,
          meta: { requiresAuth: false }
        },
        {
          path: 'edit/:id',
          name: 'BookEdit',
          component: () => import('@/views/book/BookEdit.vue'),
          props: true,
          meta: { requiresAuth: true }
        }
      ]
    }, {
      path: '/cart',
      name: 'Cart',
      component: () => import('@/views/cart/CartLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'CartList',
          component: () => import('@/views/cart/CartList.vue')
        },
        {
          path: 'add/:bookId',
          name: 'CartAdd',
          component: () => import('@/views/cart/CartAdd.vue'),
          props: true
        },
        {
          path: 'edit/:cartId/:bookId',
          name: 'CartEdit',
          component: () => import('@/views/cart/CartEdit.vue'),
          props: true
        }
      ]
    }, {
      path: '/orders',
      name: 'Orders',
      component: () => import('@/views/order/OrderList.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const token = localStorage.getItem('token')
  const userInfo = localStorage.getItem('userInfo')

  // 如果有token但store未初始化，则初始化store
  if (token && !authStore.token) {
    authStore.token = token
    if (userInfo) {
      authStore.userInfo = JSON.parse(userInfo)
    }
  }

  // 检查路由是否需要登录权限
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  // 如果路由需要登录权限且用户未登录
  if (requiresAuth && !token) {
    ElMessage.warning('请先登录')
    return next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }

  // 如果是登录页面且已经登录，重定向到首页
  if (to.path === '/login' && token) {
    return next('/')
  }

  next()
})

export default router
